package com.norma.macaron.service.oauth.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.norma.macaron.service.common.domain.user.TMenu;
import com.norma.macaron.service.common.domain.user.TRole;
import com.norma.macaron.service.common.domain.user.TUser;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.*;

/***
 * @Author zhangchaofeng
 * @Description //spring security 当前登录对象
 * @Date 14:10 2020/6/8 0008
 **/
@Getter
@Setter
public class LoginUser extends TUser implements UserDetails {

    private List<TRole> roles;

    private List<TMenu> permissions;

    public LoginUser(String username, String password, List<TRole> roles, List<TMenu> permissions) {
        super(username, password);
        this.roles = roles;
        this.permissions = permissions;
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new HashSet<>();
        if (!CollectionUtils.isEmpty(roles)) {
            roles.forEach(role -> {
                if (role.getCode().startsWith("ROLE_")) {
                    authorities.add(new SimpleGrantedAuthority(role.getCode()));
                } else {
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getCode()));
                }
            });
        }
        if(!CollectionUtils.isEmpty(permissions)){
            permissions.forEach(permission -> authorities.add(new SimpleGrantedAuthority(permission.getCode())));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        return super.getPhone();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
